<template>
  <div class="dialog">
    <!-- 新增弹框 -->
    <el-dialog
      title="新增目录"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
        <el-form-item label="所属学科" prop="subjectID">
          <el-select v-model="form.subjectID" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="form.directoryName" placeholder="请输入目录名称"></el-input>
        </el-form-item>
      </el-form> 
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {simpleSubject} from '@/api/subjects'
import {addDirectorys, directoryDetail, updateDirectory} from '@/api/directorys'
export default {
  name: 'AddDialog',
  props: {
    dialogVisible: {
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      form: {
        subjectID:'',
        directoryName:''
      },
      options:[],
      rules: {
        subjectID:[
          { required: true, message: '所属学科不能为空', trigger: 'blur' },
        ],
        directoryName:[
          { required: true, message: '目录名称不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  mounted() {
    this.getSubjectList()
  },
  methods: {
    closeDialog() {
      this.$emit('dialog-close')
      // 清空表单
      this.form = {
        subjectID:'',
        directoryName:''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    },
    // 学科列表
    async getSubjectList() {
      const res = await simpleSubject()
      // console.log('1111',res);
      this.options = res
    },
    // 确认按钮
    confirm() {
      // 兜底校验
      this.$refs.form.validate(async (valid) => {
        // console.log('校验通过');
        if (valid) {
          // 校验通过
          // 判断新增还是编辑
          if(!this.form.id) {
             // 调新增接口
          await addDirectorys(this.form)
          } else {
            // 编辑接口
            await updateDirectory(this.form)
          }
          // 提示用户
          this.$message.success(`${!this.form.id ? '新增成功': '更新成功'}`)
          // 关闭弹窗
          this.closeDialog()
          // 刷新列表
          this.$emit('updat-list')
        }
      });
    },
    // 数据回填
    async getDetail(id) {
      console.log('1',id);
      const res = await directoryDetail(id)
      console.log(res);
      this.form = res
    }
  }
}
</script>

<style>

</style>